import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/TransferMessageWithUserPage.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/component/GroupIconView.dart';
import 'package:im_app/im/page/view/component/SessionIconView.dart';
import 'package:im_app/im/page/view/component/UserIconView.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../dao/ImSessionDao.dart';
import '../../pojo/ImPojo.dart';
import '../../pojo/UiPojo.dart';
import '../../util/HexColor.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../../util/UiUtil.dart';
import '../bloc/SelectUsersCubit.dart';
import '../bloc/TransferMessageCubit.dart';
import '../view/LoadingView.dart';
import '../view/TransferMessageView.dart';
import '../view/component/SearchView.dart';
import '../view/component/cell/SessionItemSelectView.dart';

class TransferMessagePage extends StatefulWidget {
  const TransferMessagePage({super.key});

  @override
  State<StatefulWidget> createState() => _TransferMessageState();
}

class _TransferMessageState extends State<TransferMessagePage> {
  late TextEditingController _sessionTextEditingController;
  late TextEditingController _contentTextEditingController;
  late AutoScrollController _sessionScrollController;
  late AutoScrollController _selectedSessionScrollController;
  late FocusNode _sessionSearchFocusNode;

  @override
  void initState() {
    _sessionTextEditingController = TextEditingController();
    _contentTextEditingController = TextEditingController();

    var transferMessageCubit = context.read<TransferMessageCubit>();
    _sessionTextEditingController.text = transferMessageCubit.state.contentSearch;

    _sessionScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    _selectedSessionScrollController = AutoScrollController(
        viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: Axis.vertical);

    _sessionSearchFocusNode = FocusNode();
    _sessionSearchFocusNode.addListener(() {
      if (transferMessageCubit.state.contentSearch == '' && !_sessionSearchFocusNode.hasFocus) {
        transferMessageCubit.add(TransferMessageSearchableEvent(false));
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var transferMessageCubit = context.watch<TransferMessageCubit>();
    return BlocConsumer<TransferMessageCubit, TransferMessageState>(
        listener: (BuildContext context, TransferMessageState transferMessageState) {
      if (transferMessageState.forwardUrl != null) {
        Navigator.of(context).popUntil(ModalRoute.withName(transferMessageState.forwardUrl!));

        UiUtil.showSnackBar(context, '消息转发成功');
        return;
      }
      // if (transferMessageState.showTransferPane) {
      //   buildTransferPane(context, transferMessageCubit);
      // }
    }, builder: (BuildContext context, TransferMessageState state) {
      return Scaffold(
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        body: Stack(
          children: [
            // 选择会话
            _buildSessionPane(context, transferMessageCubit),
            // 搜索
            _buildSearchPane(context, transferMessageCubit),

            _buildTransferPane(context, transferMessageCubit),
          ],
        ),
      );
    });
  }

  // 构建选择会话界面
  Widget _buildSessionPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return Column(
      children: [
        _buildAppBar(context, transferMessageCubit),
        _buildSearchPaneFalse(context, transferMessageCubit),
        _buildSessionHeadPane(context, transferMessageCubit),
        Expanded(
            child: Container(
              color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
              child: CustomScrollView(
                slivers: [_buildSessionListPane(context, transferMessageCubit)],
              ),
            )
        ),
      ],
    );
  }

  Widget _buildSearchPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return Visibility(
        visible: transferMessageCubit.state.searchable,
        child: Column(
          children: [
            _buildSearchPaneTrue(context, transferMessageCubit),
            Expanded(
                child: GestureDetector(
              onTap: () {
                print("11111111111111111111111111");
              },
              child: _buildSearchResultPane(context, transferMessageCubit),
            )),
          ],
        ));
  }

  Widget _buildTransferPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    var state = transferMessageCubit.state;
    return Visibility(
        visible: transferMessageCubit.state.showTransferPane,
        child: Stack(
          children: [
             Opacity(
              opacity: 0.5,
              child: GestureDetector(
                onTap: () {
                  transferMessageCubit.add(TransferMessageCancelTransferEvent(context, false));
                },
                child: Container(
                  color: Colors.grey,
                ),
              ),
            ),
            Center(
              child: Container(
                height: 300,
                margin: const EdgeInsets.only(left: 40, right: 40),
                padding: const EdgeInsets.all(10),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                child: TransferMessageView(
                  messages: state.messages,
                  session: state.selectedSession,
                  sessions: state.selectedSessions,
                  selectType: state.selectType,
                  searchResult: state.selectSearchResult,
                  transferMessageCubit: transferMessageCubit,
                  isCreateSession: false,
                ),
              ),
            )
          ],
        ));
  }

  Widget _buildAppBar(BuildContext context, TransferMessageCubit transferMessageCubit) {
    var selectType = transferMessageCubit.state.selectType;
    var selectButtonName = selectType.name;
    var title = selectType.title;
    var fontColor = Colors.black;
    var buttonStyle = ButtonStyle();
    if (selectType == SelectType.multiple && transferMessageCubit.state.selectedSessions.isNotEmpty) {
      selectButtonName = '发送(${transferMessageCubit.state.selectedSessions.length})';
      fontColor = Colors.white;
      buttonStyle = ButtonStyle(backgroundColor: WidgetStatePropertyAll(HexColor.fromHex("#32cd32")));
    }
    return AppBar(
      leading: InkWell(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: Text(
        title,
        style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500),
      ),
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      centerTitle: true,
      actions: [
        TextButton(
          style: buttonStyle,
          onPressed: () {
            if (selectType == SelectType.multiple && transferMessageCubit.state.selectedSessions.isNotEmpty) {
              var state = transferMessageCubit.state;
              transferMessageCubit.add(TransferMessageSubmitEvent(context, false));
            } else {
              selectTypeEvent(transferMessageCubit);
            }
          },
          child: Text(
            selectButtonName,
            style: TextStyle(color: fontColor),
          ),
        )
      ],
    );
  }

  Widget _buildSearchPaneFalse(BuildContext context, TransferMessageCubit transferMessageCubit) {
    var state = transferMessageCubit.state;
    if (state.selectType == SelectType.multiple) {
      // 多选时，对聊天搜索
      return Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: SearchView<TransferMessageCubit>(
          prefix: state.selectedSessions.isNotEmpty ? _buildSelectedSessionList(transferMessageCubit) : null,
          searchHandler: _doSessionSearch,
          param: transferMessageCubit,
        ),
      );
    } else if (state.selectType == SelectType.simple && !state.searchable) {
      return GestureDetector(
        onTap: () {
          transferMessageCubit.add(TransferMessageSearchableEvent(true));
        },
        child: Container(
          height: 30,
          margin: const EdgeInsets.only(left: 10, right: 10),
          decoration: const BoxDecoration(
              color: ImConstant.IM_RESERVE_BACKGROUND_COLOR, borderRadius: BorderRadius.all(Radius.circular(10))),
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [Icon(Icons.search), Text('搜索')],
          ),
        ),
      );
    } else {
      return const Text('');
    }
  }

  Widget _buildSessionHeadPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return Padding(
      padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Text(
            '最近聊天',
            style: TextStyle(fontSize: ImConstant.IM_SMALL_SIZE),
          ),
          TextButton.icon(
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return MultiBlocProvider(providers: [
                  BlocProvider(
                    create: (context) => SelectUsersCubit(new Set<String>())..loadData(new Set<String>()),
                  ),
                  BlocProvider(
                    create: (context) => TransferMessageCubit(transferMessageCubit.state.messages, TransferType
                        .simple, TransferScene(sceneType: transferMessageCubit.state.transferScene.sceneType)),
                  ),
                ], child: const TransferMessageWithUserPage());
              }));
            },
            label: const Text('创建新的聊天', style: TextStyle(fontSize: ImConstant.IM_SMALL_SIZE)),
            icon: const Icon(Icons.add),
          )
        ],
      ),
    );
  }

  Widget _buildSessionListPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return SliverList.separated(
      itemBuilder: (BuildContext context, int index) {
        return SessionItemSelectView(
          imSession: transferMessageCubit.state.filterSessions.elementAt(index),
          selectType: transferMessageCubit.state.selectType,
        );
      },
      itemCount: transferMessageCubit.state.filterSessions.length,
      separatorBuilder: (BuildContext context, int index) => ListSeparator(
        indent: 10,
      ),
    );
  }

  Widget _buildSearchPaneTrue(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return Container(
      // padding: const EdgeInsets.all(2),
      margin: const EdgeInsets.only(right: 10, left: 10),
      height: 50,
      color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      child: SearchView<TransferMessageCubit>(
        searchHandler: _doSearch,
        param: transferMessageCubit,
        contentPadding: const EdgeInsets.only(top: 6.5, bottom: 6.5),
        suffix: GestureDetector(
          onTap: () {
            transferMessageCubit.add(TransferMessageSearchableEvent(false));
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  Widget _buildSearchResultPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    return Opacity(
      opacity: (transferMessageCubit.state.searchResultSet?.totalSize() ?? 0) > 0 ||
              transferMessageCubit.state.contentSearch != ''
          ? 1
          : 0.5,
      child: Container(
        color: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        child: _buildSearchResultsPane(context, transferMessageCubit),
      ),
    );
  }

  Widget _buildSelectedSessionList(TransferMessageCubit transferMessageCubit) {
    var state = transferMessageCubit.state;
    return ConstrainedBox(
      constraints: const BoxConstraints(maxWidth: 33 * 7),
      child: Container(
        width: 30.0 * state.selectedSessions.length + 20.0,
        height: 40,
        margin: const EdgeInsets.only(right: 10),
        child: ListView.builder(
          itemBuilder: (context, index) {
            return AutoScrollTag(
                key: ValueKey(index),
                controller: _selectedSessionScrollController,
                index: index,
                child: Container(
                  margin: const EdgeInsets.only(left: 3, top: 3, bottom: 3),
                  decoration: BoxDecoration(
                      border: Border.all(color: ImConstant.IM_MAIN_BACKGROUND_COLOR, width: 1),
                      borderRadius: const BorderRadius.all(Radius.circular(5))),
                  child: GestureDetector(
                    onTap: () async {
                      var uindex = state.allSessions.indexOf(state.selectedSessions[index]);
                      if (uindex >= 0) {
                        await _sessionScrollController.scrollToIndex(uindex);
                        _sessionScrollController.highlight(uindex);
                      }
                    },
                    child: GestureDetector(
                      onTap: () {
                        transferMessageCubit.add(TransferMessageRemoveSessionEvent(state.selectedSessions[index]));
                      },
                      child: SessionIconView(
                        session: state.selectedSessions[index],
                        iconSize: 30,
                      ),
                    ),
                  ),
                ));
          },
          physics: const AlwaysScrollableScrollPhysics(),
          controller: _selectedSessionScrollController,
          itemCount: state.selectedSessions.length,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

  Widget _buildSearchResultsPane(BuildContext context, TransferMessageCubit transferMessageCubit) {
    var children = <Widget>[];
    // 查找联系人
    if (transferMessageCubit.state.searchResultSet?.userSearchResults?.isNotEmpty ?? false) {
      var sliverAppbar = _buildSearchTitle("联系人");
      children.add(sliverAppbar);

      var length = transferMessageCubit.state.searchResultSet!.userSearchResults?.length ?? 0;
      var sliverList = _buildSliverList(context, transferMessageCubit.state.searchResultSet!.userSearchResults!,
          length, 10);
      children.add(sliverList);

      // Widget? moreWidget = _buildMorePane(length, _userMaxSize, _userDefaultSize,
      //         ()=>_userMaxSize += 10, ()=>_userMaxSize = _userDefaultSize);
      // if (moreWidget != null) {
      //   children.add(moreWidget);
      // }
    }

    // 查找用户
    if (transferMessageCubit.state.searchResultSet?.groupSearchResults?.isNotEmpty ?? false) {
      var sliverAppbar = _buildSearchTitle('群聊');

      children.add(sliverAppbar);

      var length = transferMessageCubit.state.searchResultSet!.groupSearchResults?.length ?? 0;
      var sliverList = _buildSliverList(context, transferMessageCubit.state.searchResultSet!.groupSearchResults!,
          length, 100);
      children.add(sliverList);

      // Widget? moreWidget = _buildMorePane(length, _groupMaxSize, _groupDefaultSize,
      //         ()=>_groupMaxSize += 10, ()=>_groupMaxSize = _groupDefaultSize);
      // if (moreWidget != null) {
      //   children.add(moreWidget);
      // }
    }

    if (children.isEmpty && transferMessageCubit.state.contentSearch != '') {
      var empty = const SliverToBoxAdapter(
        child: Padding(
          padding: EdgeInsets.only(left: 10),
          child: Text('查询无结果'),
        ),
      );
      children.add(empty);
    }
    return LoadingView(state: transferMessageCubit.state.state, child: CustomScrollView(slivers: children));
  }

  Widget _buildSearchTitle(String title) {
    return SliverPadding(
        padding: const EdgeInsets.only(top: 10),
        sliver: SliverToBoxAdapter(
          child: Container(
            color: Colors.black12,
            padding: const EdgeInsets.only(left: 10, top: 5, bottom: 5),
            margin: const EdgeInsets.only(top: 5, bottom: 5),
            child: Text(title),
          ),
        ));
  }

  Widget _buildSliverList(BuildContext context, List<SearchResult> searchResults, int size, int dataMaxSize) {
    var length = searchResults.length;
    var size = length;
    if (length > dataMaxSize) {
      size = dataMaxSize;
    }

    return SliverList.separated(
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
          child: _buildListTitle(context, searchResults[index]),
          onTap: () {
            print("333333333333333333");
          },
        );
      },
      itemCount: size,
      separatorBuilder: (BuildContext context, int index) {
        return ListSeparator();
      },
    );
  }

  Widget _buildListTitle(BuildContext context, SearchResult searchResult) {
    if (searchResult.groupCode != null) {
      return _buildGroupListTitle(context, searchResult);
    } else {
      return _buildUserListTitle(context, searchResult);
    }
  }

  Widget _buildUserListTitle(BuildContext context, SearchResult searchResult) {
    return ListTile(
      leading: UserIconView(user: searchResult.user!, iconSize: 40, ),
      title: Text(searchResult.userName ?? ''),
      onTap: () {
        _selectUserOrGroupAndTransferMessage(context, searchResult.user!, null);
      },
    );
  }

  Widget _buildGroupListTitle(BuildContext context, SearchResult searchResult) {
    return ListTile(
      leading: GroupIconView(group: searchResult.group!, iconSize: 40,),
      title: Text(searchResult.groupName ?? ''),
      subtitle: Text(
        searchResult.userName ?? '',
        style: const TextStyle(fontSize: 12),
      ),
      onTap: () {
        _selectUserOrGroupAndTransferMessage(context, null, searchResult.group!);
      },
    );
  }

  @override
  void dispose() {
    _sessionTextEditingController.dispose();
    _contentTextEditingController.dispose();
    _selectedSessionScrollController.dispose();
    _sessionSearchFocusNode.dispose();
    _sessionScrollController.dispose();
    super.dispose();
  }

  void selectTypeEvent(TransferMessageCubit transferMessageCubit) {
    transferMessageCubit
        .add(TransferMessageChangeSelectTypeEvent(transferMessageCubit.state.selectType.switchSelectType()));
  }

  void _doSessionSearch(dynamic? context1, String searchText) {
    if (context1 == null) return;
    var transferMessageCubit = context1 as TransferMessageCubit;
    transferMessageCubit.add(TransferMessageSessionSearchEvent(searchText));
  }

  void _doSearch(dynamic? context1, String searchText) {
    if (context1 == null) return;
    var transferMessageCubit = context1 as TransferMessageCubit;
    transferMessageCubit.add(TransferMessageSearchEvent(searchText));
  }

  void _selectUserOrGroupAndTransferMessage(BuildContext context, ImUser? user, ImGroup? group) async {
    var transferMessageCubit = context.read<TransferMessageCubit>();

    var userId = ImSingleton.getInstance().session.userId!;

    ImSession? imSession = null;

    var sessionDao = ImSessionDao();
    if (group != null) {
      imSession = await sessionDao.getByGroupCodeAndUserId(group!.code, userId);
    } else {
      var dbSession = await sessionDao.getByUserId(userId, userId, user!.userId);
      if (dbSession != null) {
        imSession = dbSession;
      } else {
        imSession = ImSession.buildWithUser(userId, user!);
        await sessionDao.batchInserts([imSession]);

        UiUtil.uiShowSession(imSession);
      }
    }
    transferMessageCubit.add(TransferMessageSelectSessionEvent(imSession!));
  }
}

void buildTransferPane(BuildContext context, TransferMessageCubit transferMessageCubit) async {
  var state = transferMessageCubit.state;
  showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text('转发消息'),
          content: SizedBox(
            height: 300,
            child: TransferMessageView(
              messages: state.messages,
              session: state.selectedSession,
              sessions: state.selectedSessions,
              selectType: state.selectType,
              searchResult: state.selectSearchResult,
              transferMessageCubit: transferMessageCubit,
              isCreateSession: true,
            ),
          ),
        );
      });
}

class TransferMessage {
  List<ImMessage> imMessages;          // 转发消息
  TransferType transferType;            // 转发类型
  TransferScene transferScene;          // 转发数据

  TransferMessage({ required this.imMessages, required this.transferType, required this.transferScene});
}

enum SelectType {
  simple('单选', '选择多个聊天'),
  multiple('多选', '选择一个聊天群'),
  ;

  final String name;
  final String title;

  const SelectType(this.name, this.title);

  SelectType switchSelectType() {
    if (this == simple) return multiple;
    return simple;
  }
}

class TransferScene {
  TransferSceneType sceneType;
  Object? data;

  TransferScene({ required this.sceneType, this.data });
}

enum TransferSceneType {
  message,        // 消息转发
  collect,        // 收藏转发
}